package com.example.ai_agent.app;

import com.example.ai_agent.advisor.myLoggerAdvisor;
import com.example.ai_agent.chatmeomory.FileBasedChatMemory;
import com.example.ai_agent.rag.LoveAppRagCustomAdvisorFactory;
import com.example.ai_agent.rag.QueryRewriter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Component;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

/**
 * @author Yan.z.h
 * @version 1.0
 */
@Component
@Slf4j
public class LoveAPP {

    private  final ChatClient chatClient;

    private  final  String SYSTEM_PROMPT="扮演深耕恋爱心理领域的专家。开场向用户表明身份，" +
            "告知用户可倾诉恋爱难题。围绕单身、恋爱、已婚三种状态提问：" +
            "单身状态询问社交圈拓展及追求心仪对象的困扰；恋爱状态询问沟通、" +
            "习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。引导用户详述事情经过、" +
            "对方反应及自身想法，以便给出专属解决方案。\n";

    /**
     * 初始化客户端
     * @param dashcopeChatModel
     */
    public LoveAPP(ChatModel  dashcopeChatModel) {
        //基于文件存储
        String fileDri = System.getProperty("user.dri")+"/temp/chat-memory";
        ChatMemory chatMemory =new FileBasedChatMemory(fileDri);
//        //基于本地内存存储
//        ChatMemory chatMemory =new InMemoryChatMemory();
        chatClient =ChatClient.builder(dashcopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory),
                        //自定义日志拦截器，可按需开启
                        new myLoggerAdvisor()
//                        //自定义重读拦截器，可按需开启
//                        new myReReadingAdvisor()
                )

                .build();
    }

    /**
     * 基础多轮对话
     * @param message
     * @param chatId
     * @return
     */

    public String doChat(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }
  record LoveReport(String userName, List<String> suggestReport) {}

    /**
     * 生成报告的多轮对话
     * @param message
     * @param chatId
     * @return
     */
    public LoveReport doChatWithReport(String message, String chatId) {
        LoveReport entity = chatClient
                .prompt()
                .system(SYSTEM_PROMPT + "每次对话后都要生成恋爱结果，标题为{用户名}，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(LoveReport.class);

        log.info("entity: {}", entity);
        return entity;
    }
    /**
     * RAG向量数据库 回答
     */
    @Resource
    private VectorStore loveAppVectorStore;
    @Resource
    private Advisor loveAppRagCloudAdvisor;
    @Resource
    VectorStore pgVectorVectorStore;
    @Resource
    QueryRewriter queryRewriter;

    public String doChatWithRag(String message, String chatId) {
        //重写用户提问
        String reWriterMessage = queryRewriter.doQueryRewrite(message);
        ChatResponse chatResponse = chatClient
                .prompt()
                //使用重写的用户提问
                .user(reWriterMessage)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new myLoggerAdvisor())
                //基于RAG 检索增强服务 基于云知识库
                //.advisors(loveAppRagCloudAdvisor)
                // 基于RAG本地知识库问答
                //.advisors(new QuestionAnswerAdvisor(loveAppVectorStore))
                //基于RAG 检索增强服务 基于PGSQL库
//                 .advisors(new QuestionAnswerAdvisor(pgVectorVectorStore))
                //基于自定义的RAG 增强顾问
                .advisors(LoveAppRagCustomAdvisorFactory
                        .createLoveAppRagCustomAdvisor(loveAppVectorStore,"单身"))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }
//AI 调用工具
    @Resource
    private ToolCallback[] allTools;

    public String doChatWithTools(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new myLoggerAdvisor())
                .tools(allTools)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }
  //使用MCP 调用工具
    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    public String doChatWithMcp(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new myLoggerAdvisor())
                .tools(toolCallbackProvider)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }








}
